import json
import os
import time

import akshare as ak


# 获取沪深股市A股实时行情
def getStockList():
    try:
        # 添加重试机制
        max_retries = 3
        for attempt in range(max_retries):
            try:
                data = ak.stock_zh_a_spot()
                # 将DataFrame转换为字典列表，每行数据转为一个字典，列名作为key
                stock_list = data.to_dict(orient='records')
                return stock_list
            except Exception as e:
                if attempt < max_retries - 1:
                    print(f"尝试 {attempt+1}/{max_retries} 失败: {e}")
                    time.sleep(2)  # 等待2秒后重试
                else:
                    raise  # 重试次数用完，抛出异常
    except Exception as e:
        print(f"获取股票数据失败: {e}")
        print(f"错误类型: {type(e).__name__}")
        print(f"错误详情: {str(e)}")
        # 返回空列表而不是直接崩溃
        return []

# 将股票数据保存到JSON文件
def save_to_json(data, filename="stock_data.json"):
    # 确保输出目录存在
    output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "output")
    os.makedirs(output_dir, exist_ok=True)

    # 构建完整的文件路径
    file_path = os.path.join(output_dir, filename)

    # 将数据写入JSON文件
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    return file_path

# 调用函数并保存结果
if __name__ == "__main__":
    result = getStockList()
    if result:
        # 保存到JSON文件
        file_path = save_to_json(result)
        print(f"成功获取到 {len(result)} 条股票数据")
        print(f"数据已保存到: {file_path}")
    else:
        print("未获取到股票数据，请检查网络连接或API可用性。")
